#include <iostream>
#include <vector>

#include "include/MemcacheProxy.h"
#include "include/Configuration.h"


void MemcacheProxy::Init()
{
	_p_memcache = new Memcache(Configuration::mmc.server, Configuration::mmc.port);
	_p_db_memcache = new Memcache(Configuration::mmc.server, Configuration::mmc.db_port);
}

void MemcacheProxy::Exit()
{
	delete _p_memcache;
	delete _p_db_memcache;
}

int MemcacheProxy::SetDbValue(string &key, string &value, int live_seconds)
{
	return SetValue(_p_db_memcache, key, value, live_seconds);
}

int MemcacheProxy::SetMemValue(string &key, string &value)
{
	return SetValue(_p_memcache, key, value, 0);
}

int MemcacheProxy::SetValue(Memcache *p_cache, string &key, string &value, int live_seconds)
{
    if(key == "")
    {
        return 1;
    }

	vector<char> vect;

	for(unsigned int i = 0; i < value.length(); i++)
	{
		vect.push_back(value[i]);
	}

	if(!_p_cache->set(key, vect, (time_t)live_seconds, 0))
	{
		return 1;
	}

	return 0;
}

int MemcacheProxy::GetDbValue(string &key, string &value)
{
	return GetValue(p_db_memcache, key, value);
}

int MemcacheProxy::GetMemValue(string &key, string &value)
{
	return GetValue(p_memcache, key, value);
}

int MemcacheProxy::GetValue(Memcache *p_cache, string &key, string &value)
{
    if(key == "")
    {
        return 1;
    }

	vector<char> vect;

	if(!_p_cache->get(key, vect))
	{
		return 1;
	}

	value.clear();

	for(unsigned int i = 0; i < vect.size(); i++)
	{
		value.push_back(vect[i]);
	}

	// test
	cout << "get value from memcache: " << value << endl;

	return 0;
}

int MemcacheProxy::RemoveDbValue(string &key)
{
	return RemoveValue(p_db_memcache, key);
}

int MemcacheProxy::RemoveMemValue(string &key)
{
	return RemoveValue(p_memcache, key);
}

int MemcacheProxy::RemoveValue(Memcache *p_cache, string &key)
{
    if(key == "")
    {
        return 1;
    }

	_p_memcache->remove(key);

	return 0;
}

int MemcacheProxy::AppendDbValue(string &key, string &value)
{
	return AppendValue(p_db_memcache, key, value);
}

int MemcacheProxy::AppendMemValue(string &key, string &value)
{
	return AppendValue(p_memcache, key, value);
}

int MemcacheProxy::AppendValue(Memcache *p_cache, string &key, string &value)
{
    if(key == "")
    {
        return 1;
    }

	vector<char> vect;

	for(unsigned int i = 0; i < value.length(); i++)
	{
		vect.push_back(value[i]);
	}

	if(!_p_memcache->append(key, vect))
	{
		return 1;
	}

	return 0;
}
